package com.xhtranslate.service.youdao.serviceImpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhtranslate.common.config.TranslateConfig;
import com.xhtranslate.common.util.FileUtil;
import com.xhtranslate.common.util.AddUseLimitThreadUtil;
import com.xhtranslate.service.youdao.service.YoudaoOcrService;
import com.xhtranslate.service.youdao.util.YoudaoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 有道ocr服务impl
 *
 * @author liuxuhuang
 * @date 2022/11/17 15:22:43
 */
@Service
@Slf4j
public class YoudaoOcrServiceImpl implements YoudaoOcrService {
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private YoudaoUtil youdaoUtil;
    @Autowired
    private AddUseLimitThreadUtil addUseLimitThreadUtil;

    @Override
    public Map<String, String> ocrImg(MultipartFile file) throws IOException {
        Map<String, String> map = new HashMap<>();
        /**
         * 封装参数
         */
        File file2 = fileUtil.saveImg(file);
        String absolutePath = file2.getAbsolutePath();
        String base64Img = fileUtil.imgToBase64(absolutePath);
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        String salt = String.valueOf(System.currentTimeMillis());
        String signStr = TranslateConfig.YoudaoAppId + youdaoUtil.truncate(base64Img) + salt + curtime + TranslateConfig.YoudaoSecreKey;
        String sign = youdaoUtil.getDigest(signStr);
        Map<String, String> params = packingParams(base64Img, curtime, salt, sign);
        /**
         * 请求有道OCR接口
         */
        String object = youdaoUtil.requestForHttp(TranslateConfig.YoudaoOcrRequestUrl, params);
        JSONObject jsonObject = JSONObject.parseObject(object);
        String errorCode = jsonObject.getString("errorCode");
        /**
         * 异常返回异常代码和提示
         */
        if (!errorCode.equals("0")) {
            map.put("errorCode", errorCode);
            map.put("msg", jsonObject.getString("msg"));
            return map;
        }
        /**
         * 返回正常结果
         */
        StringBuilder stringBuilder = new StringBuilder();
        JSONArray regions = jsonObject.getJSONObject("Result").getJSONArray("regions");
        for (int i = 0; i < regions.size(); i++) {
            JSONArray lines = regions.getJSONObject(0).getJSONArray("lines");
            for (int i2 = 0; i2 < lines.size(); i2++) {
                String text = lines.getJSONObject(i2).getString("text");
                stringBuilder.append(text).append("\n");
            }
        }
        String string = stringBuilder.toString();
        addUseLimitThreadUtil.addCreditLimit(TranslateConfig.YoudaoOcrRedisName, string.length());
        map.put("errorCode", errorCode);
        map.put("data", string);
        log.info("有道ocr识别结果");
        log.info(string);
        log.info(map.toString());
        return map;
    }

    public Map<String, String> packingParams(String base64Img, String curtime, String salt, String sign) {
        Map<String, String> params = new HashMap<>();
        params.put("detectType", "10012");
        params.put("imageType", "1");
        params.put("langType", "auto");
        params.put("img", base64Img);
        params.put("docType", "json");
        params.put("signType", "v3");
        params.put("curtime", curtime);
        params.put("appKey", TranslateConfig.YoudaoAppId);
        params.put("salt", salt);
        params.put("sign", sign);
        return params;
    }
}
